﻿using System;
using System.Collections.Generic;
using System.Text;
using VideoCache.Aggregation.Interfaces;
using Fsb.Utility;

namespace VideoCache.Aggregation.Implements
{
    [Site("qq.com")]
    class QQFetcher
    {
        public string GetToken(string url)
        {
            string token = this.GetTokenByUrl(url);

            if (string.IsNullOrEmpty(token))
            {
                return this.GetTokenByPlayer(url);
            }

            return token;
        }

        private string GetTokenByUrl(string url)
        {
            string html = HttpUtility.Get(url, Encoding.UTF8);

            string json = StringUtility.SubString(html, "var VIDEO_INFO=", ";");

            if (!string.IsNullOrEmpty(json))
            {
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(json);

                return jObject["vid"].ToString().Trim('\"');
            }

            return null;
        }

        private string GetTokenByPlayer(string url)
        {
            // http://imgcache.qq.com/tencentvideo_v1/player/TencentPlayer.swf?max_age=86400&v=20121230&vid=s00112zerle&autoplay=1&list=2&duration=2593&adplay=1&cid=3bcnhqamutpfqh9&showcfg=1&tpid=2&share=1&shownext=1&title=%E7%81%B5%E4%B9%A6%E5%A6%99%E6%8E%A2%E7%AC%AC%E4%BA%94%E5%AD%A3%20%E7%AC%AC01%E9%9B%86&ptag=%7Cindex.ver_nav.tv&outhost=http%3A%2F%2Fv.qq.com%2Fcover%2F3%2F3bcnhqamutpfqh9.html

            return UrlHelper.GetParameter(url, "vid");
        }
    }
}
